#!/usr/bin/python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


class Component(PluginComponent):

    def __init__(self, parent):
        # read:  self.is_peripheral()
        # write: self.set_peripheral()
        self.__bPeripheral = False

    def filled_properties(self, item):
        if "is_peripheral" in item:
            if not item["is_peripheral"]:
                raise ConfigError("invalid component found in file %s" % (cls._FULLFN))
            self.set_peripheral(item["is_peripheral"], pre_ready_call=True)

    def is_peripheral(self):
        assert self._readyCheck(False)

        if self.__bPeripheral:
            return True

        # FIXME
        if not self._realDumb and self._realOfflineReason is None:
            if self.get_peer_machine_connector() is not None:
                if self.get_peer_machine_connector().is_peripheral_connector():
                    return True

        return False

    def set_peripheral(self, value, pre_ready_call=False):
        assert self._readyCheck(pre_ready_call)

        # pre-set check
        if value:
            assert len(self._connectors) > 0

        # do set
        if value == self.__bPeripheral:
            return
        self.__bPeripheral = value

        if not pre_ready_call:
            # FIXME: record to file
            pass


class Connector(PluginConnector):

    def __init__(self, parent):
        # read:  self.is_peripheral_connector()
        # write: self.set_peripheral_connector()
        self._bPeripheral = False

    def filled_properties(self, item):
        if "is_peripheral_connector" in item:
            if not item["is_peripheral_connector"]:
                raise ConfigError("invalid connector found in file %s" % (cls._FULLFN))
            self.set_peripheral(item["is_peripheral_connector"], pre_ready_call=True)
